package com.bblocks.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import org.slf4j.MDC;

/**
 * 日志追踪(基于MDC 即ThreadLocal)
 * http://dockone.io/article/1640913
 */
public class TraceIdUtils {
	public static final String TRACE_ID = "traceId";
	private static final int MAX_ID_LENGTH = 10;

	/**
	 * 生成 traceId
	 */
	private static String genTraceId() {
		//return RandomStringUtils.randomAlphanumeric(MAX_ID_LENGTH);

		return IdUtil.nanoId(10);
	}

	/**
	 * 设置 traceId
	 */
	public static void setTraceId(String traceId) {
		// 如果参数为空，则生成新 ID
		traceId = StrUtil.isBlank(traceId) ? genTraceId() : traceId;
		// 将 traceId 放到 MDC 中
		//MDC.put(TRACE_ID, StrUtil.subSufByLength(traceId,MAX_ID_LENGTH));
		MDC.put(TRACE_ID, traceId);
	}

	public static void setTraceId(String method,String traceId){
		setTraceId(null,method,traceId);
	}

	/**
	 *
	 * @param identity
	 * @param method
	 * @param traceId
	 */
	public static void setTraceId(String identity,String method,String traceId){
		traceId = StrUtil.isBlank(traceId) ? genTraceId() : traceId;

		if(StrUtil.isNotEmpty(method))
			setTraceId( (StrUtil.isNotEmpty(identity)?(identity+":"):"") + method+"_"+traceId);
		else
			setTraceId( (StrUtil.isNotEmpty(identity)?(identity+":"):"")+traceId);
	}


	/**
	 * 获取 traceId
	 * @param needCreate
	 * @return
	 */
	public static String getTraceId(boolean needCreate) {
		// 获取
		String traceId = MDC.get(TRACE_ID);
		if(needCreate) {
			// 如果 traceId 为空，则生成新 ID
			return StrUtil.isBlank(traceId) ? genTraceId() : traceId;
		}else
			return traceId;
	}

	/**
	 * 线程技术移除
	 * @return
	 */
	public static void endTraceId() {
		MDC.remove(TRACE_ID);
	}


	 public static void main(String[] args){
		System.out.println();
		 IdUtil.fastSimpleUUID();
		 IdUtil.fastUUID();
		 IdUtil.getSnowflake();
		 IdUtil.nanoId();
		 IdUtil.randomUUID();
		 IdUtil.simpleUUID();
		 IdUtil.getDataCenterId(1000L);

		 System.out.println(IdUtil.fastSimpleUUID());
		 System.out.println(IdUtil.fastUUID());
		 System.out.println(IdUtil.getSnowflake());
		 System.out.println(IdUtil.nanoId());
		 System.out.println(IdUtil.nanoId(10));
		 System.out.println(IdUtil.randomUUID());
		 System.out.println(IdUtil.simpleUUID());
		 System.out.println(IdUtil.getDataCenterId(1000L));

		 System.out.println(SecureUtil.md5("key1111111111111111111"));
	 }
}